package img

import (
	"crypto/md5"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	// "runtime"
	// "time"

	"github.com/garyburd/redigo/redis"
	_ "github.com/go-sql-driver/mysql"
)

const (
	DataRoot     = "/home/acfun/goprojects/src/sora/dataDst/" // 存放封面图的根目录
	TimeoutLimit = 10                                         // 设置超时时间
)

// 表示章节ID和封面URL的对应关系
type Image struct {
	VolumeID string
	Url      string
}

func Save(vc Image) {
	h := md5.New()
	h.Write([]byte(vc.Url))
	img_name := fmt.Sprintf("%x", h.Sum(nil))
	// 创建文件
	dst, err := os.OpenFile(DataRoot+vc.VolumeID+"/img/"+img_name+".jpg", os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_EXCL, 0644)
	//dst, err := os.Create(DataRoot + vc.VolumeID + "/img/" + img_name + ".jpg")
	if err != nil {
		return
	}
	res, err := http.Get(vc.Url)
	defer res.Body.Close()
	if err != nil {
		fmt.Println(err)
	}
	// 生成文件
	io.Copy(dst, res.Body)
	// goroutine通信
	fmt.Println(vc.VolumeID, vc.Url)
}

func Start() error {
	// 构建队列
	imgs := getUrlFromRedis()
	// start goroutines
	//ch := make(chan bool, len(imgs))
	for _, img := range imgs {
		Save(img)
	}
	return nil
}

func getUrlFromRedis() []Image {
	c, err := redis.Dial("tcp", ":6379")
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	// 从zset中获取内容到img
	values, err := redis.Values(c.Do("ZRANGE", "sora:qimg", 0, -1, "WITHSCORES"))
	if err != nil {
		fmt.Println(err)
	}
	imgs := make([]Image, len(values)/2)
	for i, v := range values {
		if i%2 == 0 { // url
			imgs[i/2].Url = string(v.([]byte))
		} else { // vid
			imgs[i/2].VolumeID = string(v.([]byte))
			//fmt.Println(i/2, imgs[i/2].VolumeID)
		}
	}
	//c.Do("ZREMRANGEBYRANK", "sora:qimg", 0, -1)
	return imgs
}
